package com.geek.novel.activity.main

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Message
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.geek.novel.R
import com.geek.novel.activity.CollectActivity
import com.geek.novel.activity.SettingsActivity
import com.geek.novel.activity.TestPageActivity
import com.geek.novel.activity.base.BaseActivity
import com.geek.novel.activity.book.BookDownloadActivity
import com.geek.novel.activity.book.BookSearchActivity
import com.geek.novel.activity.main.operate.LoginOperator
import com.geek.novel.common.Constant
import com.geek.novel.dialog.MainMenuDialog
import com.geek.novel.entity.CrawlerSource
import com.geek.novel.fragment.BaseFragment
import com.geek.novel.fragment.FragmentBookCategory
import com.geek.novel.fragment.FragmentBookShop
import com.geek.novel.fragment.FragmentMyBook
import com.geek.novel.network.RslHandler
import com.geek.novel.services.CrawlerSourceService
import com.geek.novel.services.NovelService
import com.geek.novel.services.manager.VersionUpdateManager
import com.geek.novel.utils.FormatUtil
import com.geek.novel.utils.LogCatUtil
import com.geek.novel.utils.SPUtil
import com.geek.novel.utils.ToastUtils
import com.geek.novel.view.loading.LoadingDialogUtil
import com.geek.novel.vo.ApiErrorResult
import com.geek.novel.vo.ApiResult
import com.mingyuers.permission.PermissionAnywhere
import com.zackratos.ultimatebarx.ultimatebarx.addStatusBarTopPadding
import kotlinx.android.synthetic.main.activity_main.*


open class MainActivity : BaseActivity(), RslHandler {

	/**登录授权相关操作*/
	private lateinit var loginOperator: LoginOperator
	/**更新的管理器*/
	private lateinit var versionUpdateManager: VersionUpdateManager

	/**回退键退出程序的监听时间*/
	private val systemExitTime = 1000

	/**小说服务*/
	private lateinit var novelService: NovelService

	/**主页菜单*/
	private lateinit var mainMenuDialog: MainMenuDialog

	/**爬虫源的数据服务*/
	private val crawlerSourceService = CrawlerSourceService()

	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_main)

		//初始化控件
		initV()

		//添加菜单
		addMenus()

		//主页菜单
		mainMenuDialog = MainMenuDialog(this)
		mainMenuDialog.onCreateView()

		//初始化服务对象
		novelService = NovelService(this)

		//获取所有爬虫源
		novelService.getCrawlerSourceList()

	}

	/**
	 * 销毁App时把更新服务也销毁掉
	 */
	override fun onDestroy() {
		LogCatUtil.d("???", "销毁MainActivity")
		versionUpdateManager.stopService()
		super.onDestroy()
	}

	/**
	 * 初始化控件
	 */
	@SuppressLint("InflateParams")
	private fun initV(){
		//设置容器适配沉浸式状态栏
		ly_top_bar.addStatusBarTopPadding()
		layout_userInfo.addStatusBarTopPadding()

		//默认添加主页的fragment，记录用户的选择并跳转
		val userSelectFragment = SPUtil[SPUtil.main_fragment_user_select, SPUtil.SP_SYSTEM_SETUP]
		if(userSelectFragment == FragmentBookShop.FragmentName){
			this.pageToBookShop()
		}else{
			this.pageToMyBook()
		}

		//首页顶部字体加粗
		tv_main_title.paint.isFakeBoldText = true

		//关闭侧滑菜单栏的拖拽事件
		slideHolder.setAllowInterceptTouch(false)
		//顶部头像图标点击切换出侧滑菜单
		btn_slide_menu.setOnClickListener{
			slideHolder.toggle()
		}

		//设置按钮点击事件
		layout_setting.setOnClickListener{
			startActivityForResultByAnim(this@MainActivity, SettingsActivity::class.java, Constant.ACTIVITY_RESULT_SETTING)
		}

		//搜索按钮点击事件
		btn_search.setOnClickListener{
			startActivityByAnim(this@MainActivity, BookSearchActivity::class.java)
		}

		//显示主页菜单
		btn_main_menu.setOnClickListener{
			val position = IntArray(2)
			it.getLocationOnScreen(position)//获取控件的坐标
			val x = FormatUtil.isNullToIntZero(position[0]).toFloat()
			val y = FormatUtil.isNullToIntZero(position[1]).toFloat() + it.height
			mainMenuDialog.openDialog(Gravity.NO_GRAVITY, x, y)
		}

		/*获取权限*/
		PermissionAnywhere.requestPermission(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
			_, _, _ ->
			run {
				//登录功能相关
				this.initLogin()
				//更新功能相关
				this.checkUpdate()
			}
		}

		//初始化测试功能(主要是用于进入测试页面)
		this.initTestBlock()

	}

	/**测试页面的点击次数*/
	private var testPageClickNum = 0
	/**初始化测试功能*/
	private fun initTestBlock(){
		view_test_page_block.setOnClickListener {
			testPageClickNum++
			if(testPageClickNum == 10){
				testPageClickNum = 0
				startActivityByAnim(this, TestPageActivity::class.java)
			}
		}
	}

	/**登录功能相关*/
	private fun initLogin(){
		loginOperator = LoginOperator(this)
		loginOperator.init()
	}

	/**更新功能相关*/
	private fun checkUpdate(){
		versionUpdateManager = VersionUpdateManager.getInstance(this)
		versionUpdateManager.checkUpdate(false)
	}

	/**Activity回显*/
	override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
		LogCatUtil.d(this.javaClass.name, "onActivityResult")

		super.onActivityResult(requestCode, resultCode, data)
		mainMenuDialog.onActivityResult(requestCode, resultCode, data)

		//刷新头像信息
		loginOperator.onActivityResult(requestCode, resultCode, data)

	}

	/**
	 * 添加菜单
	 */
	private fun addMenus(){
		//我的收藏
		initMenu(MenuItem(getString(R.string.slidingmenu_collection), R.drawable.icon_slidingmenu_collection, CollectActivity::class.java, Constant.ACTIVITY_RESULT_COLLECT))
		//缓存记录
		initMenu(MenuItem(getString(R.string.slidingmenu_book_download), R.drawable.icon_slidingmenu_collect, BookDownloadActivity::class.java))
//		//我的消息
//		initMenu(MenuItem(getString(R.string.slidingmenu_message), R.drawable.icon_slidingmenu_news, CollectActivity::class.java))
//		//我的钱包
//		initMenu(MenuItem(getString(R.string.slidingmenu_wallet), R.drawable.icon_slidingmenu_purse, WelcomeActivity::class.java))
//		//我的订单
//		initMenu(MenuItem(getString(R.string.slidingmenu_order), R.drawable.icon_slidingmenu_order, CollectActivity::class.java))
//		//我的预约
//		initMenu(MenuItem(getString(R.string.slidingmenu_bespeak), R.drawable.icon_slidingmenu_bespeak, CollectActivity::class.java))
	}

	@SuppressLint("InflateParams")
	private fun initMenu(item: MenuItem){
		//填充菜单项的布局
		val view = layoutInflater.inflate(R.layout.view_slidingmenu_item, null)

		view.findViewById<TextView>(R.id.tv_menu_item_text).text = item.text
		view.findViewById<ImageView>(R.id.iv_menu_item_icon).setImageDrawable(ContextCompat.getDrawable(this, item.icon))

		view.setOnClickListener{
			startActivityForResultByAnim(this@MainActivity, item.toClass, item.resultCode)
		}
		layout_menu.addView(view)

	}

	/**侧滑菜单的菜单项*/
	inner class MenuItem(var text: String, var icon: Int, var toClass: Class<out Any>, var resultCode: Int=0)


	/**
	 * 底部按钮点击事件
	 */
	open fun pageToMyBook() {
		changePageAndUpdatePageName(FragmentMyBook.newInstance())
	}
	open fun pageToBookShop() {
		changePageAndUpdatePageName(FragmentBookShop.newInstance())
	}
	open fun pageToBookCategory() {
		changePageAndUpdatePageName(FragmentBookCategory.newInstance())
	}

	/**
	 * 跳转页面
	 */
	private fun changePageAndUpdatePageName(fragment: BaseFragment){
		tv_main_title.text = fragment.pageName()
		replaceFrag(R.id.fl_container, fragment)

		//记录用户当前所在的页面
		SPUtil.put(SPUtil.main_fragment_user_select, fragment.fragmentName(), SPUtil.SP_SYSTEM_SETUP)

		//添加观察者
		this.addEventObserver(fragment)
	}

	/**
	 * 绑定事件
	 */
	override fun bindEvent() {
		layout_page_to_my_book.setOnClickListener(this)
		layout_page_to_book_shop.setOnClickListener(this)
		layout_page_to_book_category.setOnClickListener(this)
	}

	override fun clickEvent(id: Int, v: View) {
		when(id){
			R.id.layout_page_to_my_book->{
				this.pageToMyBook()
			}
			R.id.layout_page_to_book_shop->{
				this.pageToBookShop()
			}
			R.id.layout_page_to_book_category->{
				this.pageToBookCategory()
			}
		}
	}

	/**
	 * 监听回退键
	 * 再按一次退出程序
	 */
	private var exitTime: Long = 0
	override fun onBackPressed() {
		if(slideHolder != null && slideHolder.isOpened){
			slideHolder.close()
		}else{
			if(System.currentTimeMillis() - exitTime > systemExitTime){
				exitTime = System.currentTimeMillis()
				ToastUtils.toast(getString(R.string.system_exit_prompt))
			}else{
				super.onBackPressed()
			}
		}
	}

	/**处理消息*/
	override fun handleMessage(msg: Message) {
		//接收事件，然后广播出去，目的是让所有子fragment能接收到消息
		this.notifyEvent(msg)
	}

	override fun onError(code: Int, err: ApiErrorResult) {
	}

	override fun onSuccess(result: ApiResult, code: Int) {
		when(code){
			//获取所有爬虫源
			Constant.HTTP_KEY_APP_GET_CRAWLER_SOURCE_LIST->{
				val list = result.getList(CrawlerSource::class.java)
				if(list.isEmpty()){
					ToastUtils.toast("书源获取失败！请检查是否使用了旧版APP！")
					return
				}
				crawlerSourceService.saveList(list)
			}
		}
	}
}